<!-- sign_in -->
<template>
  <div class="container b-container" id="b-container">
    <form class="form" id="b-form" @submit.prevent="handleLogin">
      <h2 class="form_title title">Sign in to Website</h2>
      <div class="form__icons">
        <img class="form__icon" src=" " />
        <img class="form__icon" src=" " />
        <img class="form__icon" src=" " />
      </div>
      <span class="form__span">or use your email account</span>
      <input class="form__input" type="text" placeholder="用户名" v-model="loginForm.username" />
      <input class="form__input" type="password" placeholder="密码" v-model="loginForm.password" />
      <a class="form__link">Forgot your password?</a>
      <button class="form__button button submit" type="submit">SIGN IN</button>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useRouter } from 'vue-router';
import useEmitter from "../../../hooks/useEmitter.js";
import { ElMessage } from 'element-plus';

const router = useRouter();
const isOpen = ref(true);
const emitter = useEmitter();

const loginForm = ref({
  username: "",
  password: "",
});

const handleLogin = async () => {
  try {
    const response = await fetch('http://localhost:3456/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: loginForm.value.username,
        password: loginForm.value.password
      })
    });

    const data = await response.json();
    
    if (response.ok) {
      ElMessage.success('登录成功');
      localStorage.setItem('user', JSON.stringify(data.user));
      router.push('/model');
    } else {
      ElMessage.error(data.message || '登录失败');
    }
  } catch (error) {
    console.error('登录错误:', error);
    ElMessage.error('登录失败，请稍后重试');
  }
};

onMounted(() => {
  emitter.on("change", (newIsOpen) => {
    isOpen.value = newIsOpen;
    const bContainer = document.querySelector("#b-container");
    if (bContainer) {
      bContainer.classList.toggle("is-txl");
      bContainer.classList.toggle("is-z200");
    }
  });
});
</script>

<style scoped lang="scss">
@import "./login.scss";
</style>